/**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 * }
 */
/**
 * 二叉搜索树，依旧中序遍历，有序数组取第k小的值
 * @param {TreeNode} root
 * @param {number} k
 * @return {number}
 */
var kthSmallest = function (root, k) {
    let stack = [],
        temp = root;

    while (stack.length > 0 || temp !== null) {
        while (temp !== null) {
            stack.push(temp)
            temp = temp.left
        }

        let node = stack.pop()
        if (--k === 0) {
            return node.val
        }
        temp = node.right
    }
};





/**
 * 中序递归
 * @param {TreeNode} root
 * @param {number} k
 * @return {number}
 */
var kthSmallest = function (root, k) {
    return findKthLevel(root, [k]).val
};

const findKthLevel = (root, k) => {
    let a = root.left && findKthLevel(root.left, k)
    if (--k[0] === 0) {
        return root
    }
    let b = root.right && findKthLevel(root.right, k)
    return a || b
}